<?php
session_start();
require_once dirname(__FILE__) . "/../lib/Mail.php";
include dirname(__FILE__) . "/config.php";

/*
 * Auther: Ahmed Ibrahim
 * Function to get current url without any parameters
 */

function full_url() {
    $s = &$_SERVER;
    $ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on') ? true : false;
    $sp = strtolower($s['SERVER_PROTOCOL']);
    $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
    $port = $s['SERVER_PORT'];
    $port = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':' . $port;
    $host = isset($s['HTTP_X_FORWARDED_HOST']) ? $s['HTTP_X_FORWARDED_HOST'] : isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : $s['SERVER_NAME'];
    return $protocol . '://' . $host . $port . $s["REQUEST_URI"];
}

/*
 * Auther: Sameh Serag
 * Function to get URLs
 */

function getUrls($username = null) {
    $urlsArray = array();
    $numberOfLevels = 1;
//get number of levels
    $result = mysql_query("SELECT `value` from `option` WHERE `key`='number_of_levels'");
    if (mysql_num_rows($result) > 0) {
        $numberOfLevels = mysql_fetch_array($result);
        $numberOfLevels = $numberOfLevels['value'];
    }

// get ceratin urls
    if ($username) {
        $url1 = mysql_query("SELECT * from user WHERE username= '" . mysql_real_escape_string($username) . "'");
        if (mysql_num_rows($url1) > 0) {
            $sponsAd = getSponserLink();          
            $urlsArray[] = $sponsAd;
            $user = mysql_fetch_array($url1);
            $urlsArray[] = $user;

            if ($user['parent_id']) {
                for ($index = 2; $index <= $numberOfLevels; $index++) {

                    $result = mysql_query("SELECT * from user WHERE id=" . $user['parent_id']);
                    if (@mysql_num_rows($result) > 0) {
                        $user = mysql_fetch_array($result);
                        $urlsArray[] = $user;
                    } else {
                        //get rest from default
                        for ($index1 = $index; $index1 <= $numberOfLevels; $index1++) {
                            $result = mysql_query("SELECT * from ads WHERE level = $index1 ORDER BY RAND() LIMIT 1");
                            if (mysql_num_rows($result) > 0) {
                                $entry = mysql_fetch_array($result);
                                $urlsArray[] = $entry;
                            }
                        }
                        break;
                    }
                }
            } else {
                for ($index = 2; $index <= $numberOfLevels; $index++) {
                    $result = mysql_query("SELECT * from ads WHERE level = $index ORDER BY RAND() LIMIT 1");
                    if (mysql_num_rows($result) > 0) {
                        $entry = mysql_fetch_array($result);
                        $urlsArray[] = $entry;
                    }
                }
            }
        } else {
            $sponsAd = getSponserLink();
            $urlsArray[] = $sponsAd;
            for ($index = 1; $index <= $numberOfLevels; $index++) {
                $result = mysql_query("SELECT * from ads WHERE level = $index ORDER BY RAND() LIMIT 1");
                if (mysql_num_rows($result) > 0) {
                    $entry = mysql_fetch_array($result);
                    $urlsArray[] = $entry;
                }
            }
        }
    }
    // get default urls
    else {
        $sponsAd = getSponserLink();
            $urlsArray[] = $sponsAd;
        for ($index = 1; $index <= $numberOfLevels; $index++) {
            $result = mysql_query("SELECT * from ads WHERE level = $index ORDER BY RAND() LIMIT 1");
            if (mysql_num_rows($result) > 0) {
                $entry = mysql_fetch_array($result);
                $urlsArray[] = $entry;
            }
        }
    }
    return $urlsArray;
}

/*
 * Auther: Sameh Serag
 * Function to save new account
 */

function saveNewAccount($formData) {
    $name = $formData['name'];
    $username = $formData['username'];
    $email = $formData['email'];
    $password = $formData['password'];
    $url = $formData['url'];
    $textAd = $formData['textAd'];
    $hash = md5(md5(md5(rand(0, 1000))));

    if ($formData['refName']) {
        $numberOfLevels = 1;
        //get number of levels
        $result = mysql_query("SELECT numberOfLevels from admin");
        if (mysql_num_rows($result) > 0) {
            $numberOfLevels = mysql_fetch_array($result);
            $numberOfLevels = $numberOfLevels['numberOfLevels'];
        }
        $ref = mysql_query("SELECT * from user WHERE username= '" . mysql_real_escape_string($formData['refName']) . "'");
        if (mysql_num_rows($ref) > 0) {
            $refUser = mysql_fetch_array($ref);
            // save this account to user table
            $qry = "INSERT INTO user (id, name, username, password, hash, email, textAd, url, parent_id) VALUES ('', '$name', '$username', '$password', '$hash', '$email','$textAd','$url', '" . $refUser['id'] . "')";
            mysql_query($qry);
            $userId = mysql_insert_id();
            $qry = "INSERT INTO affiliate (id, child_id, parent_id, level) VALUES ('', '$userId', '" . $refUser['id'] . "', 1)";
            mysql_query($qry);

            $level = 2;
            while (isset($refUser['parent_id']) && $refUser['parent_id'] && $level <= $numberOfLevels) {
                $ref = mysql_query("SELECT * from user WHERE id= '" . $refUser['parent_id'] . "'");
                $refUser = mysql_fetch_array($ref);
                if ($refUser) {
                    $qry = "INSERT INTO affiliate (id, child_id, parent_id, level) VALUES ('', '$userId', '" . $refUser['id'] . "', '$level')";
                    mysql_query($qry);
                    $level++;
                }
            }
        }
        // no parent    
    } else {
        $qry = "INSERT INTO user (id, name, username, password, hash, email, textAd, url) VALUES ('', '$name', '$username', '$password', '$hash','$email','$textAd','$url')";
        mysql_query($qry);
    }

    //get all options
    $options = mysql_query("SELECT * FROM `option`");
    $allOprionsArray = array();
    while ($option = mysql_fetch_array($options)) {
        $allOprionsArray[$option['key']] = $option['value'];
    }

    //send email
    $result = mysql_query("SELECT * from mail_template WHERE code='confirmation_email'");
    $mailTemplate = mysql_fetch_array($result);
    $search = array('{name}', '{username}', '{password}', '{email}', '{sitename}', '{siteurl}', '{validationurl}');
    $replace = array($name, $username, $password, $email, $allOprionsArray['site_name'], $allOprionsArray['site_url'], $allOprionsArray['site_url'] . '/confirm.php?username=' . $username . "&hash=" . $hash);
    $body = str_replace($search, $replace, $mailTemplate['body']);
    $subject = str_replace($search, $replace, $mailTemplate['subject']);
    sendMail($email, $subject, $body);


    $_SESSION['name'] = $name;
    $_SESSION['email'] = $email;
    header('location: thanks.php');
}

function sendMail($to, $subject, $body) {

    $headers = array('From' => $GLOBALS['_From'], 'To' => $to, 'Subject' => $subject);
    $smtp = @Mail::factory('smtp', array(
                'host' => $GLOBALS['_Host'],
                'port' => $GLOBALS['_Port'],
                'auth' => true,
                'username' => $GLOBALS['_Username'],
                'password' => $GLOBALS['_Password']
            ));
    $mail = @$smtp->send($to, $headers, $body);

    if (@PEAR::isError($mail)) {
        return 'false';
    } else {
        return 'true';
    }
}

/*
 * Auther: Sameh Serag
 * Add Ordinal Suffix PHP Function
 */

function addOrdinalNumberSuffix($num) {
    if (!in_array(($num % 100), array(11, 12, 13))) {
        switch ($num % 10) {
            // Handle 1st, 2nd, 3rd
            case 1: return $num . 'st';
            case 2: return $num . 'nd';
            case 3: return $num . 'rd';
        }
    }
    return $num . 'th';
}

/*
 * Auther: Sameh Serag
 * Random string
 */

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

function getSponserLink() {
    $sponserLink = mysql_query("SELECT * from ads WHERE `level`=0 AND status=1 AND `assigned` != 0 ORDER BY updated_at LIMIT 1");

    if (!mysql_num_rows($sponserLink)) {
        $sponserLink = mysql_query("SELECT * from ads WHERE `level`=0 AND status=1 AND `assigned` = 0 ORDER BY updated_at LIMIT 1");
    }

    $sponserLink = mysql_fetch_array($sponserLink);

    $qry = "UPDATE `ads` SET `updated_at`= now()  WHERE `id` ='" . $sponserLink['id'] . "'";
    mysql_query($qry);
    
    return $sponserLink;
}